<template>
    <div class="container">
        <n-card title="问题列表">
            <template #header-extra>
                <n-button ghost type="primary" @click="handleUpdateBatch">批量审核通过</n-button>
            </template>
            <n-data-table
                ref="table"
                :bordered="false"
                :columns="columns"
                :data="questionList"
                :loading="loadingRef"
                :paginate-single-page="false"
                :pagination="paginationReactive"
                :row-key="(row) => row.id"
                :striped="true"
                remote
                size="large"
                @update:filters="handleFiltersChange"
                @update:sorter="handleSorterChange"
                @update:checked-row-keys="handleCheck"
            />
        </n-card>
    </div>
</template>

<script setup>
import { NButton, useDialog, useMessage } from 'naive-ui'
import { h, onMounted, reactive, ref } from 'vue'
import { deleteQuestion, listQuestionsByState, partialUpdateQuestion, partialUpdateQuestionList } from '../api/question'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()
const dialog = useDialog()
const createColumns = () => {
    return [
        {
            type: 'selection',
        },
        {
            title: '发布日期',
            key: 'createTime',
            sortOrder: false,
            sorter: true,
        },
        {
            title: '提问者',
            ellipsis: {
                tooltip: true,
            },
            key: 'username',
        },
        {
            title: '标题',
            ellipsis: {
                tooltip: true,
            },
            key: 'title',
        },
        {
            title: '操作',
            key: 'actions',
            render (row) {
                return ['查看', '通过', '删除'].map(item => {
                    if (item === '通过' && !row.state) {
                        return h(NButton, {
                            style: { marginRight: '0.5vw' },
                            strong: true,
                            tertiary: true,
                            size: 'small',
                            type: 'primary',
                            onClick: () => {
                                partialUpdateQuestion(row.id, { state: 1 }).then(res => {
                                    if (res.code === '200') {
                                        loadingRef.value = true
                                        fetchQuestions()
                                        message.success('审核通过！')
                                    }
                                })
                            },
                        }, { default: () => item })
                    } else if (item === '查看') {
                        return h(NButton, {
                            style: { marginRight: '0.5vw' },
                            strong: true,
                            tertiary: true,
                            size: 'small',
                            type: 'info',
                            onClick: () => {
                                router.push(`/questions/${row.id}`)
                            },
                        }, { default: () => item })
                    } else if (item === '删除') {
                        return h(NButton, {
                            style: { marginRight: '0.5vw' },
                            strong: true,
                            tertiary: true,
                            size: 'small',
                            type: 'error',
                            onClick: () => {
                                dialog.warning({
                                    title: '警告',
                                    content: '三思而后行！',
                                    positiveText: '确定',
                                    negativeText: '不确定',
                                    onPositiveClick: () => {
                                        deleteQuestion(row.id).then(res => {
                                            if (res.code === '204') {
                                                loadingRef.value = true
                                                fetchQuestions()
                                                message.success('它终究还是没能躲过..😭')
                                            }
                                        })
                                    },
                                    onNegativeClick: () => {
                                        message.info('幸好，此帖躲过一劫！😁')
                                    },
                                })
                            },
                        }, { default: () => item })
                    }
                })
            },
        },
    ]
}
const columns = createColumns()
const questionList = ref([])
const loadingRef = ref(true)
const paginationReactive = reactive({
    page: 1,
    pageCount: 1,
    pageSize: 10,
    showSizePicker: true,
    itemCount: 0,
    pageSizes: [10, 15, 20, 25, 30],
    prefix ({ itemCount }) {
        return `共有 ${itemCount} 个问题待审核 `
    },
    onChange: (page) => {
        paginationReactive.page = page
        fetchQuestions()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        fetchQuestions()
    },
})
const fetchQuestions = (sorter = 'latest') => {
    loadingRef.value = true
    listQuestionsByState(paginationReactive.page, paginationReactive.pageSize, 0, sorter).then(res => {
        paginationReactive.page = res.data.current
        paginationReactive.pageSize = res.data.size
        paginationReactive.pageCount = res.data.pages
        paginationReactive.itemCount = res.data.total
        questionList.value = res.data.records.map((element, index) => {
            return {
                id: element.id,
                index: ++index,
                title: element.title,
                username: element.username,
                isTop: element.isTop,
                createTime: dayjs(element.createTime).format('YYYY-MM-DD'),
            }
        })
        loadingRef.value = false
    })
}
const handleFiltersChange = () => {

}
const handleSorterChange = (sorter) => {
    if (!sorter || sorter.columnKey === 'createTime') {
        if (sorter.order === 'descend') {
            fetchQuestions('latest')
        } else {
            fetchQuestions('earliest')
        }
        columns[0].sortOrder = !sorter ? false : sorter.order
    }
}

const checkedRowKeys = ref([])
const handleCheck = (rowKeys) => {
    checkedRowKeys.value = rowKeys
}

const handleUpdateBatch = () => {
    partialUpdateQuestionList(checkedRowKeys.value).then(res => {
        if (res.code === '200') {
            fetchQuestions()
            message.success('全部审核通过！')
        }
    })
}

onMounted(() => {
        fetchQuestions()
    },
)
</script>

<style scoped>
</style>
